from func.reviewer.reviewer import LiteratureReviewer
#from src.sys_prompt import REVIEWER_SYSTEM_PROMPT

import os
import concurrent.futures
from pathlib import Path
from tqdm import tqdm
from func.reviewer.cozebot import CozeBot

def load_literature2():

    # 假设 lite_review 目录下只有一个 md 文件，或者你需要指定具体的文件名
    lite_review_dir = '../lite_review'

    # 获取目录下的所有文件
    files = os.listdir(lite_review_dir)

    # 过滤出 md 文件
    md_files = [f for f in files if f.endswith('.md')]

    if md_files:
        # 假设我们只处理第一个 md 文件
        md_file_path = os.path.join(lite_review_dir, md_files[0])
        
        # 读取文件内容
        with open(md_file_path, 'r', encoding='utf-8') as file:
            query = file.read()
        
        return query
    else:
        print("没有找到 md 文件")
        return None


def assemble_enquiry_from_files(output_dir):
    """
    从output目录下读取所有以_analysis.txt结尾的文件，并按指定格式组装字符串。
    :param output_dir: 输出目录路径
    :return: 拼接的字符串
    """
    enquiry = ""
    
    # 获取output目录下所有以_analysis.txt结尾的文件
    files_to_process = [f for f in Path(output_dir).rglob("*_analysis.txt")]
    
    for file_path in files_to_process:
        # 读取每个文件的内容作为评价
        with open(file_path, 'r', encoding='utf-8') as f:
            evaluation = f.read()
        
        # 获取文件名
        filename = file_path.name
        
        # 按指定格式组装字符串
        enquiry += f"文件名: {filename}\n评价: {evaluation}\n\n"
    
    return enquiry
def process_files(bot, input_dir, output_dir, message_text):
    """
    扫描输入目录中的 .md 和 .txt 文件，检查 output 目录是否已有对应的 _analysis.txt 文件。
    如果没有，则调用 CozeBot 进行上传并获取回复，结果保存到 output 目录。
    """
    # 获取输入目录中所有 .md 和 .txt 文件
    files_to_process = [f for f in Path(input_dir).rglob("*") if f.suffix in ['.md', '.txt']]

    # 过滤出还没有 _analysis.txt 结果的文件
    files_to_upload = []
    for file_path in files_to_process:
        analysis_file = Path(output_dir) / f"{file_path.stem}_analysis.txt"
        if not analysis_file.exists():
            files_to_upload.append(file_path)

    print(f"Found {len(files_to_upload)} files to process (excluding existing analysis files).")
    if not files_to_upload:
        print("All files have been processed already.")
        return []

    all_file_evaluations = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        with tqdm(total=len(files_to_upload), desc="Processing files") as pbar:
            for file_path in files_to_upload:
                futures.append(executor.submit(upload_and_generate_reply, bot, file_path, message_text, output_dir, pbar, all_file_evaluations))

            for future in concurrent.futures.as_completed(futures):
                future.result()

    return all_file_evaluations


def upload_and_generate_reply(bot:CozeBot, file_path, message_text, output_dir, pbar, all_file_evaluations:list):
    """
    上传文件到 CozeBot，获取回复并保存到 output 目录。
    """
    print(f"正在处理文件: {file_path}")

    file_id = bot.upload_file(file_path)
    if file_id:
        response = bot.chat_with_coze(message_text, file_id)
        if response:
            output_file = Path(output_dir) / f"{file_path.stem}_analysis.txt"
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(response)
            print(f"保存回复到: {output_file}")
            all_file_evaluations.append((file_path.name, response))
        else:
            print(f"未生成回复，文件: {file_path}")
    else:
        print(f"文件上传失败，跳过: {file_path}")

    pbar.update(1)


if __name__ == '__main__':
    input_dir = 'input'
    output_dir = 'output'  # 输出目录路径
    message_text = "请按照评分规则分析如下论文"
    bot = CozeBot()
    
    
    #topic = "The_current_status_and_prospects_of_text2sql_applications_in_maritime_affairs"
    #prompt = REVIEWER_SYSTEM_PROMPT.format(topic = topic)
    #print(prompt)
    
    # 处理文件
    process_files(bot, input_dir, output_dir, message_text)

    # 处理所有文件，并综合对比评价
    enquiry = assemble_enquiry_from_files(output_dir)
    reviewer = LiteratureReviewer()
    print(reviewer.call_openai(enquiry))